package Ergodic;

import java.util.ArrayList;
import java.util.List;
public class Possion_Question {
	public static final int FistGlassCapacity=8;	//第一杯水容量
	public static final int SecondGlassCapacity=5;	//第二杯水容量
	public static final int ThirdGlassCapacity=3;	//第三杯水容量
	public static final int GoalSize=4;	//目标水量
	
	public List<List<Integer>> histories = new ArrayList<List<Integer>>(); //保存已有的状态，对已有的状态，就不再向下继续遍历，这样可以节省求解时间。
    private List<Glass> glasses = new ArrayList<Glass>();
    class Glass {
        int capacity; // 容量
        int size; // 拥有水量
        public Glass(int capacity) {
            this.capacity = capacity;
        }        
    }
    private void addHistory() {//增加历史记录
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(glasses.get(0).size);
        list.add(glasses.get(1).size);
        list.add(glasses.get(2).size);
        histories.add(list);
    }
    private boolean isHistory() {//判断是否为历史状态
        for (List<Integer> history : histories) {
            if (history.get(0) == glasses.get(0).size && history.get(1) == glasses.get(1).size && history.get(2) == glasses.get(2).size) {
                return true;
            }
        }
        return false;
    }
    public boolean pour(Glass from, Glass to) {//倒水
        int temp1 = from.size;// 保留初始值
        int temp2 = to.size;
        if (from.size == 0 || to.capacity == to.size) {// form 中没水或 to 中已满
            return false;
        }
        int toResidual = to.capacity - to.size;
        if (from.size >= toResidual) { // 对方倒满
            to.size = to.capacity;
            from.size -= toResidual;
        } else { // 自己倒完
            to.size += from.size;
            from.size = 0;
        }
        if (isHistory()) {// 还原
            from.size = temp1;
            to.size = temp2;
            return false;
        }
        return true;
    }
    public void test() {
        Glass a = new Glass(FistGlassCapacity);
        a.size = 8;
        Glass b = new Glass(SecondGlassCapacity);
        Glass c = new Glass(ThirdGlassCapacity);
        glasses.add(a);
        glasses.add(b);
        glasses.add(c);
        addHistory();
        while (true) {
        	for(int i = 0; i < glasses.size(); i++){
        		for (int j = 0; j < glasses.size(); j++){
                    if (a.size == GoalSize || b.size == GoalSize || c.size == GoalSize) {
                        return;
                    }
        			if(i!=j){
        				if(pour(glasses.get(i),glasses.get(j))){
        					addHistory();
        					break;
        				}
        			}
        		}
        	}
        }
    }
}